//
//  HRZHomeViewController.m
//  EMarket
//
//  Created by 石头 on 2018/5/7.
//  Copyright © 2018年 好日子. All rights reserved.
//

#import "HRZHomeViewController.h"

// Controllers
#import "HRZSearchMainViewController.h"
// Models
#import "HRZHomeItemBaseModel.h"
#import "HRZHomeRecommentBaseItem.h"
// Views
#import "SDCycleScrollView.h"
#import "HRZHomeRecommendCell.h"
#import "HRZHomeFunctionCell.h"
// Vendors

// Categories
#import "UIView+SPExtension.h"
// Others
#import "HRZGlobalNetManager.h"

@interface HRZHomeViewController ()<SDCycleScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, HRZHomeRecommendCellDelegate>
{
    NSMutableArray <HRZHomeItemModel *>*_goodsAdArray;
}

@property (nonatomic, strong) UIView *topSearchView;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UIButton *messageButton;

@property (nonatomic, strong) UITableView *mTableView;
@property (nonatomic, strong) NSMutableDictionary *dicHeight;
/** 商品种类数组 */
@property (nonatomic, strong) HRZHomeItemBaseModel *homeData;

/** 广告页面 */
@property (nonatomic, strong) SDCycleScrollView *bannerAd;
@property (nonatomic, strong) NSArray <HRZHomeRecommentBaseItem *>*bannerData;


@end

static NSString *const HRZHomeRecommendCellId = @"HRZHomeRecommendCell";
static NSString *const HRZHomeFunctionCellID = @"HRZHomeFunctionCellID";

@implementation HRZHomeViewController

#pragma mark - LazyLoad


#pragma mark - LifeCyle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    
    self.isHidenNaviBar = YES;
    
    [self setNaviBar];
    
    [self.view addSubview:self.topSearchView];
    [self.view addSubview:self.mTableView];
    [self.view addSubview:self.messageButton];
    
    _goodsAdArray = [[NSMutableArray alloc] init];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setUpData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Public

#pragma mark - Private

/** 获取数据 */
- (void)setUpData {
    WEAKSELF
    [[HRZGlobalNetManager getGlobalNetManager] homePageInfoComplete:^(HRZHomeItemBaseModel *result, BOOL isSuc) {
        if (isSuc && result) {
        
            weakSelf.homeData = result;
            
            for (HRZHomeItemModel *item in result.itemModels) {
                if (item.type == HomeItemTypeCarousel) {
                    weakSelf.bannerData = item.items;
                } else {
                    [_goodsAdArray addObject:item];
                }
            }
            
            [weakSelf.mTableView reloadData];
        } else {
            HRZHomeItemBaseModel *res =[HRZHomeItemBaseModel initBaseModel];
            for (HRZHomeItemModel *item in res.itemModels) {
                if (item.type == HomeItemTypeCarousel) {
                    weakSelf.bannerData = item.items;
                } else {
                    [_goodsAdArray addObject:item];
                }
            }
            
            [weakSelf.mTableView reloadData];
        }
    }];;
    
}

- (void)setNaviBar {
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -15;
    
    UIButton *button = [[UIButton alloc] init];
    [button setImage:[UIImage imageNamed:@"mshop_message_gray_icon"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"mshop_message_gray_icon"] forState:UIControlStateHighlighted];
    button.frame = CGRectMake(0, 0, 44, 44);
    [button addTarget:self action:@selector(messButtonBarItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.rightBarButtonItems = @[negativeSpacer, backButton];
}



#pragma mark - <自定义方法>

#pragma mark - Setter


#pragma mark - ----------<Action>---------
- (void)onSearchButtonClick {
    HRZSearchMainViewController *searchVC = [[HRZSearchMainViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:NO];
}

- (void)messButtonBarItemClick {
    
}

#pragma mark - ----------  Delegate  ----------


#pragma mark - ----  UITabelViewDeleaget  ----
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _goodsAdArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_goodsAdArray.count == indexPath.section) {
        HRZHomeFunctionCell *cell = [tableView dequeueReusableCellWithIdentifier:HRZHomeFunctionCellID];
        cell.functionItemBlock = ^(NSInteger index) {
            NSLog(@"%ld", (long)index);
        };
        return cell;
    }
    
    HRZHomeItemModel *model = [_goodsAdArray objectAtIndex:indexPath.section];
    HRZHomeRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:HRZHomeRecommendCellId forIndexPath:indexPath];
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.model = model;
    
    return cell;
}

#pragma mark - ----  HRZHomeRecommendCellDelegate  ----
- (void)updateTabelViewCellHeight:(HRZHomeRecommendCell *)cell andHeight:(CGFloat)height andIndexPath:(NSIndexPath *)indexPath {
    if (![self.dicHeight[indexPath] isEqualToNumber:@(height)]) {
        self.dicHeight[indexPath] = @(height);
        [self.mTableView reloadData];
    }
}

- (void)didSelectItemAtIndexPath:(NSIndexPath *)indexPath withContentItem:(HRZHomeItemModel *)content {
    NSLog(@"%@ section = %ld, row = %ld", content, indexPath.section, indexPath.row);
}

#pragma mark - TableViewHeader - Set
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0 && _bannerData.count) return 180;
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0 && _bannerData.count) return self.bannerAd;
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_goodsAdArray.count == indexPath.section) {
        return 160;
    }
    
    if (self.dicHeight[indexPath]) {
        NSNumber *num = self.dicHeight[indexPath];
        return [num floatValue];
    } else {
        return 40;
    }
}


#pragma mark - -------<SDCycleScrollViewDelegate>-------
/** 点击AD图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    UIViewController *newVC = [[UIViewController alloc] init];
    newVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:newVC animated:YES];
}


#pragma mark - ----  Getter/Setter  ----
- (NSMutableDictionary *)dicHeight{
    if (!_dicHeight) {
        _dicHeight = [[NSMutableDictionary alloc] init];
    }
    return _dicHeight;
}

- (UITableView *)mTableView{
    if (!_mTableView) {
        _mTableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _mTableView.frame = CGRectMake(0, HRZTopNavH, kScreenWidth, kScreenHeight - HRZTopNavH - HRZBottomTabH);
        
        _mTableView.tableFooterView = [UIView new];
        _mTableView.showsVerticalScrollIndicator = NO;
        _mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_mTableView registerClass:[HRZHomeRecommendCell class] forCellReuseIdentifier:HRZHomeRecommendCellId];
        [_mTableView registerClass:[HRZHomeFunctionCell class] forCellReuseIdentifier:HRZHomeFunctionCellID];
        
        _mTableView.delegate = self;
        _mTableView.dataSource = self;
    }
    return _mTableView;
}

- (NSArray<HRZHomeRecommentBaseItem *> *)bannerData {
    if (_bannerData) {
        _bannerData = [[NSArray alloc] init];
    }
    return _bannerData;
}

- (SDCycleScrollView *)bannerAd {
    
    NSMutableArray *urlStringArray = [NSMutableArray new];
    for (HRZHomeRecommentBaseItem *model in _bannerData) {
        [urlStringArray addObject:model.itemImageUrl ?model.itemImageUrl: @"www"];
    }
    
    NSArray *imagesURLStrings = [NSArray arrayWithArray:urlStringArray];
    
    if (!_bannerAd && imagesURLStrings.count) {
        _bannerAd = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 180) delegate:self placeholderImage:[UIImage imageNamed:@"default"]];
        _bannerAd.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        _bannerAd.currentPageDotColor = [UIColor whiteColor];
        _bannerAd.imageURLStringsGroup = imagesURLStrings;
    }
    
    return _bannerAd;
}

- (UIButton *)messageButton{
    if (!_messageButton) {
        _messageButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_messageButton setTitle:@"🆕" forState:0];
        [_messageButton setTitleColor:[UIColor lightGrayColor] forState:0];
        _messageButton.titleLabel.font = PFR12Font;
        [_messageButton setImage:[UIImage imageNamed:@""] forState:0];
        [_messageButton adjustsImageWhenHighlighted];
        _messageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [_messageButton addTarget:self action:@selector(messButtonBarItemClick) forControlEvents:UIControlEventTouchUpInside];
        _messageButton.frame = CGRectMake(kScreenWidth - 44, 20, 44, 44);
    }
    return _messageButton;
}

- (UIView *)topSearchView{
    if (!_topSearchView) {
        _topSearchView = [[UIView alloc] init];
        _topSearchView.backgroundColor = HRZBGColor;
        _topSearchView.layer.cornerRadius = 5;
        [_topSearchView.layer masksToBounds];
        _topSearchView.frame = CGRectMake(10, 26, kScreenWidth - 54, 32);
        
        _searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_searchButton setImage:[UIImage imageNamed:@"icon_search"] forState:UIControlStateNormal];
        [_searchButton setTitle:@"搜索商品" forState:0];
        [_searchButton setTitleColor:[UIColor lightGrayColor] forState:0];
        _searchButton.titleLabel.font = PFR12Font;
        [_searchButton adjustsImageWhenHighlighted];
        _searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _searchButton.titleEdgeInsets = UIEdgeInsetsMake(0, 2* HRZMargin, 0, 0);
        _searchButton.imageEdgeInsets = UIEdgeInsetsMake(0, HRZMargin, 0, 0);
        [_searchButton addTarget:self action:@selector(onSearchButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _searchButton.frame = CGRectMake(0, 0, _topSearchView.sp_width - 2 * HRZMargin, _topSearchView.sp_height);
        [_topSearchView addSubview:_searchButton];
    }
    return _topSearchView;
}

@end
